#!/usr/bin/env python
import sys
import os
import uuid
import pika
import json

COMPUTE_EXCHANGE = "vulcanus-iaas-compute"
LOG_EXCHANGE = "vulcanus-iaas-log"


class TestRpcClient(object):
    def __init__(self):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        self.channel.exchange_declare(exchange=COMPUTE_EXCHANGE, type='topic', durable=True)
        queue_name = "rpc_callback_queue"
        result = self.channel.queue_declare(queue=queue_name, durable=True)
        self.callback_queue = result.method.queue
        self.channel.queue_bind(exchange=COMPUTE_EXCHANGE, queue=queue_name,
                                routing_key="vulcanus.instance.query.result")
        self.channel.basic_consume(self.on_response, no_ack=True, queue=self.callback_queue)

    def __del__(self):
        self.channel.close()
        self.connection.close()

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())
        self.channel.basic_publish(exchange=COMPUTE_EXCHANGE, routing_key='vulcanus.instance.query',
                                   properties=pika.BasicProperties(
                                       reply_to="vulcanus.instance.query.result",
                                       correlation_id=self.corr_id
                                   ),
                                   body=n)
        while self.response is None:
            self.connection.process_data_events()
        return self.response


if __name__ == '__main__':
    t_rpc = TestRpcClient()
    print(" [x] Requesting test")
    query_request = {
        "accessKeyId": "LTAIr599QLK8bBhU",
        "accessKeySecret": "HD8PRGYt1WIOJhqIbLF89bQoO8g4uK",
        "regionId": "cn-hangzhou",
        "operation": "DescribeInstances",
        "taskCode": "aaa",
        "instanceId": "bbb",
        "username": "ccc"
    }
    response = t_rpc.call(json.dumps(query_request))
    print(" [.] Got %r" % response)
